﻿using DataServer.CommonLib.Constants;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using Config.RazorLib.Services;

namespace Config.RazorLib
{
    public static class ServiceCollectionExtensions
    {
        public static void AddDataServerBlazor(this IServiceCollection services)
        {
            services.AddScoped<ExampleJsInterop>();

            services.AddAuthorizationCore(options =>
            {
                RegisterPermissionClaims(options);
            });

            services.AddTransient<IDatabaseService, DatabaseService>();
            services.AddTransient<IDataSourceService, DataSourceService>();
            services.AddTransient<IDataConfigService, DataConfigService>();
            services.AddTransient<IDimensionService, DimensionService>();
            services.AddTransient<IConfigDataService, ConfigDataService>();
        }

        private static void RegisterPermissionClaims(AuthorizationOptions options)
        {
            foreach (var prop in typeof(ApiRoutes).GetNestedTypes().SelectMany(c =>
                                 c.GetFields(BindingFlags.Public | BindingFlags.Static |
                                             BindingFlags.FlattenHierarchy)))
            {
                options.AddPolicy(prop.Name,
                    policy => policy.RequireClaim("Permission",
                        prop.Name));
            }
        }
    }
}